import Utils from "../utils/Utils";

const {isNil, isEmpty, assign, defaultTo, prefixName} = Utils;

class ULine implements UComponent {
  
  get name(): string {
    return this.options.name
  }
  
  get zIndex(): number {
    return this.options.zIndex
  }
  
  options: Required<UComponent.LineOpt> = {
    zIndex: 1,
    name: prefixName('u_line'),
    pointList: [
      [0, 0],
      [0, 0]
    ],
    curvatureA: null,
    curvatureB: null,
    lineWidth: 1,
    color: '#000000',
    dashLine: [],
    dashLineOffset: 0
  }

  visible: boolean = true

  constructor(uLineOpt?: UComponent.LineOpt) {
    this.setOption(uLineOpt)
  }

  draw(ctx: CanvasRenderingContext2D) {
    const {pointList, lineWidth, color, dashLine, dashLineOffset, curvatureA, curvatureB} = this.options
    ctx.save()

    ctx.strokeStyle = color
    ctx.lineWidth = lineWidth

    const [start, end] = pointList

    ctx.beginPath()

    if (!isEmpty(dashLine)) {
      ctx.setLineDash(dashLine)
      ctx.lineDashOffset = dashLineOffset
    }

    ctx.moveTo(...start)

    if (curvatureA && isNil(curvatureB)) {
      ctx.quadraticCurveTo(...curvatureA, ...end)
    } else if (curvatureA && curvatureB) /* 三次贝塞尔曲线 */ {
      ctx.bezierCurveTo(...curvatureA, ...curvatureB, ...end)
    } else if (isNil(curvatureA) && isNil(curvatureB)) {
      ctx.lineTo(...end)
    }

    ctx.stroke()
    ctx.closePath()
    ctx.restore()
  }

  
  /**
   * 设置图形参数
   * @param uLineOption
   */
  setOption(uLineOption?: Partial<UComponent.LineOpt>) {
    this.options = assign(this.options, defaultTo(uLineOption, {})) as Required<UComponent.LineOpt>
  }
}

export default ULine
